using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TFS.Kanban.Domain;
using TFS.Kanban.Domain.Services;

namespace TFS.Kanban.VS2010.Services
{
    public class UserStoryService : IUserStoryService
    {
        private const string UserStoryType = "User Story";
        private readonly IWorkItemService _workItemService;

        public UserStoryService(IWorkItemService workItemService)
        {
            _workItemService = workItemService;
        }

        public IEnumerable<IUserStory> GetUserStories(IProject project)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<IUserStory> GetUserStories(IIteration iteration)
        {
            return GetUserStories(_workItemService.GetWorkItems(iteration.Path, UserStoryType));
        }

        public IEnumerable<IUserStory> GetUserStories(IArea area)
        {
            return GetUserStories(_workItemService.GetWorkItems(area.Path, UserStoryType));
        }

        private IEnumerable<IUserStory> GetUserStories(IEnumerable<WorkItem> workItems)
        {
            var userStories = new HashSet<IUserStory>();

            foreach (var workItem in workItems.Where(workItem => workItem.Type.Name == UserStoryType))
            {
                userStories.Add(new UserStory
                {
                    Id = workItem.Id,
                    Name = workItem.Title,
                    State = workItem.State,
                    Tasks = GetUserStoryTasks(workItem.WorkItemLinks)
                });
            }

            return userStories;
        }

        private IEnumerable<ITask> GetUserStoryTasks(WorkItemLinkCollection workItemLinks)
        {
            var tasks = new HashSet<ITask>();

            foreach (WorkItemLink workItemLink in workItemLinks)
            {
                var workItem = _workItemService.GetWorkItem(workItemLink.TargetId);

                tasks.Add(new Task
                {
                    Id = workItem.Id,
                    Name = workItem.Title,
                    Comment = workItemLink.Comment
                });
            }

            return tasks;
        }
    }
}